﻿using SqlSugar;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using XMFramework.Models;
using XMFramework.MysqlService;

namespace XMFramework.Forms.Pages
{
    public partial class FRecipe : UIPage
    {
        private SqlSugarScope db = SqlSugarHelper.Db;
        List<RecipeModel> orderlist = new List<RecipeModel>();
        DataTable mold_dt = new DataTable();//模具表
        public FRecipe()
        {
            InitializeComponent();
            //***********内部表格,必须代码添加（模具编号）**************
            //**************过滤*************
            uiComboDataGridView1.ItemSize = new Size(480, 300);
            uiComboDataGridView1.ShowFilter = true;
            uiComboDataGridView1.FilterColumnName = "mouldCode"; //不设置则全部列过滤

            //uiComboDataGridView1.DataGridView.Init();
            uiComboDataGridView1.DataGridView.AddColumn("id", "id");
            uiComboDataGridView1.DataGridView.AddColumn("mouldCode", "mouldCode");
            uiComboDataGridView1.DataGridView.AddColumn("singleNumber", "singleNumber");
            uiComboDataGridView1.DataGridView.AddColumn("notes", "notes");
            uiComboDataGridView1.DataGridView.Columns["id"].HeaderText = "系统编号";
            uiComboDataGridView1.DataGridView.Columns["mouldCode"].HeaderText = "模具编号";
            uiComboDataGridView1.DataGridView.Columns["singleNumber"].HeaderText = "模具产品数";
            uiComboDataGridView1.DataGridView.Columns["notes"].HeaderText = "备注";
            uiComboDataGridView1.DataGridView.Columns["id"].Visible = false;
            uiComboDataGridView1.DataGridView.Columns["id"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["mouldCode"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["singleNumber"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            uiComboDataGridView1.DataGridView.Columns["notes"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            //设置表格
            uiComboDataGridView1.DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            uiComboDataGridView1.DataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            uiComboDataGridView1.DataGridView.ReadOnly = true;
            uiComboDataGridView1.DataGridView.AllowUserToAddRows = false;
            
        }

        private void FRecipe_Initialize(object sender, EventArgs e)
        {
            //每次打开页面初始化
            uiDatePicker1.Text = DateTime.Now.ToString("yyyy-MM-dd");
            try
            {
                db.BeginTran();

                mold_dt = db.Queryable<MoldModel>().Select(it => new { it.id, it.mouldCode, it.singleNumber, it.notes }).OrderBy(it => it.id, OrderByType.Desc).ToDataTable();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }
            
            uiComboDataGridView1.DataGridView.DataSource = mold_dt;

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                db.BeginTran();
                orderlist = db.Queryable<RecipeModel>().OrderBy(it => it.id, OrderByType.Desc).ToList();
                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            uiDataGridView1.DataSource = orderlist;
            uiSymbolButton2.Enabled = false;
            uiSymbolButton5.Enabled = false;
        }

        private void uiDataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1)
            {
                uiTextBox3.Text = uiDataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString();//id
                uiTextBox1.Text = uiDataGridView1.Rows[e.RowIndex].Cells["processCode"].Value.ToString();//工艺编号
                uiTextBox2.Text = uiDataGridView1.Rows[e.RowIndex].Cells["epsDensity"].Value.ToString();//原料密度
                uiComboDataGridView1.Text = uiDataGridView1.Rows[e.RowIndex].Cells["mouldCode"].Value.ToString();//模具编号
                uiTextBox8.Text = uiDataGridView1.Rows[e.RowIndex].Cells["singleNumber"].Value.ToString();//模具产品数
                uiTextBox6.Text = uiDataGridView1.Rows[e.RowIndex].Cells["notes"].Value.ToString();//备注

                uiSymbolButton2.Enabled = true;
                uiSymbolButton5.Enabled = true;
                UIMessageTip.ShowOk("调用 - 状态");
            }
        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {

            //新增按钮
            RecipeModel dataList = new RecipeModel()
            {
                processCode = uiTextBox1.Text,
                epsDensity = uiTextBox2.Text,
                mouldCode = uiComboDataGridView1.Text,
                singleNumber = Convert.ToInt32(uiTextBox8.Text),
                creationDate = Convert.ToDateTime(uiDatePicker1.Text),
                notes = uiTextBox6.Text
            };

            try
            {
                db.BeginTran();

                var x = db.Storageable(dataList)
                    .WhereColumns(it => new { it.processCode })
                    .ToStorage();
                x.AsInsertable.ExecuteCommand();//不存在插入
                //x.AsUpdateable.IgnoreColumns(z => z.id).ExecuteCommand();//存在更新

                db.CommitTran();
                if (x.InsertList.Count > 0)
                    UIMessageTip.ShowOk("新增工艺 - 成功");
                else
                    UIMessageTip.ShowWarning("已有工艺 - 警告");

            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton5_Click(object sender, EventArgs e)
        {
            //更新按钮
            try
            {
                db.BeginTran();

                bool datafalg = db.Queryable<ProductionOrderModel>()
                    .Any(it => it.recipeCode == uiTextBox1.Text);

                if (datafalg == true)
                {
                    UIMessageTip.ShowWarning("工艺已绑定订单 - 无法更新");
                }
                else
                {
                    int count = db.Updateable<RecipeModel>()
                    .SetColumns(it => new RecipeModel()
                    {
                        processCode = uiTextBox1.Text,
                        epsDensity = uiTextBox2.Text,
                        mouldCode = uiComboDataGridView1.Text,
                        singleNumber = Convert.ToInt32(uiTextBox8.Text),
                        creationDate = Convert.ToDateTime(uiDatePicker1.Text),
                        notes = uiTextBox6.Text
                    })
                    .Where(it => it.id == Convert.ToInt32(uiTextBox3.Text)).ExecuteCommand();

                    if (count > 0)
                        UIMessageTip.ShowOk("更新工艺 - 成功");
                    else
                        UIMessageTip.ShowWarning("未查询到工艺 - 警告");
                }
                db.CommitTran();

            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton2_Click(object sender, EventArgs e)
        {
            //删除按钮
            try
            {
                db.BeginTran();
                bool datafalg = db.Queryable<ProductionOrderModel>()
                    .Any(it => it.recipeCode == uiTextBox1.Text);

                if (datafalg == true)
                {
                    UIMessageTip.ShowWarning("工艺已绑定订单 - 无法删除");
                }
                else
                {
                    int count = db.Deleteable<RecipeModel>().Where(it => it.id == Convert.ToInt32(uiTextBox3.Text)).ExecuteCommand();
                    if (count > 0)
                        UIMessageTip.ShowOk("删除设备 - 成功");
                    else
                        UIMessageTip.ShowWarning("未查询到设备 - 警告");
                }
                db.CommitTran();

            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiSymbolButton3_Click(object sender, EventArgs e)
        {
            //搜索按钮
            try
            {
                db.BeginTran();

                uiDataGridView1.DataSource = db.Queryable<RecipeModel>().
                    Where(it => it.processCode.Contains(uiTextBox5.Text) && it.epsDensity.Contains(uiTextBox4.Text) && it.mouldCode.Contains(uiTextBox7.Text)).
                    OrderBy(it => it.id, OrderByType.Desc).ToList();

                db.CommitTran();
            }
            catch (Exception ex)
            {
                db.RollbackTran();//数据回滚
                UIMessageTip.ShowError("插入失败 - 数据回滚!\n" + ex);
            }

            uiSymbolButton2.Enabled = false;
            uiSymbolButton5.Enabled = false;
        }

        private void uiSymbolButton4_Click(object sender, EventArgs e)
        {
            //清除按钮
            uiTextBox5.Clear();//工艺编号
            uiTextBox4.Clear();//原料密度
            uiTextBox7.Clear();//模具编号

            if (!backgroundWorker1.IsBusy)
                backgroundWorker1.RunWorkerAsync();
        }

        private void uiComboDataGridView1_ValueChanged(object sender, object value)
        {
            if (value != null)
            {
                uiComboDataGridView1.Text = mold_dt.Rows[((DataGridViewRow)value).Index]["mouldCode"].ToString();//模具编号
                uiTextBox8.Text = mold_dt.Rows[((DataGridViewRow)value).Index]["singleNumber"].ToString();//模具产品数
            }
        }

        
    }
}
